<?php

/**
 
 * Think 标准模式公共函数库(3.0dzh开始增加的部分)
 * @category   Think
 * @package  Common
 * @author   liu21st <liu21st@gmail.com>
 * @version  $Id$
 */ 

/**
 * 格式化成欧洲金额(意大利)
 *
 * @param string $money
 * @param int $flag 1 入库，0 输出
 * @return string $length
 * @return string $partition 分隔符 是否有分隔符
 */
function moneyFormat($money,$flag=0,$length=2,$partition=true){
	if (empty($length) || $length<=0 || is_array($length)){
		$length		=	0;
	}
	/// 通过$flag判断是入库还是输出，入库时所有数字转为000.00的格式，输出时所有数字转成000.000,00格式
	switch ($flag){
		case 0:
			///是否带分隔符
			if ($partition){
				///					if(C('digital_format')=='zh') {
				$money	= number_format($money, $length);
				///					} else {
				///						$money 	= number_format($money,$length, ',', '.');
				///					}
			}else{
				///					if(C('digital_format')=='zh') {
				$money	= number_format($money,$length,'.', '');
				///					} else {
				///						$money 	= number_format($money,$length,',', '');
				///					}
			}
			break;
		case 1:///入库操作
		/// 判断用户是哪种输入格式，如是欧洲金额格式则转换成中文格式
		$money = str_replace(',','.',$money);
		break;
		case 2:
			if (strpos($money,'.')){ $money = str_replace('.',',',$money);	}
			break;
	}

	return $money;
}

/**
 *  对查询结果集进行排序
 *
 * @access    public
 * @param     array     $list 查询结果
 * @param     string    $field 排序的字段名
 * @param     array     $sortby 排序类型
 *            asc正向排序 desc逆向排序 nat自然排序
 * @return    array
 */
function list_sort_by($list, $field, $sortby='asc') {
	if(is_array($list)){
		$refer = $resultSet = array();
		foreach ($list as $i => $data)
		$refer[$i] = &$data[$field];
		switch ($sortby) {
			case 'asc': /// 正向排序
			asort($refer);
			break;
			case 'desc':/// 逆向排序
			arsort($refer);
			break;
			case 'nat': /// 自然排序
			natcasesort($refer);
			break;
		}
		foreach ( $refer as $key=> $val)
		$resultSet[] = &$list[$key];
		return $resultSet;
	}
	return false;
}

/**
 * 将提交的数据进行html格式编码
 * @param string $str 处理的字符串
 * @return string 
 */
function specConvertStr ($str) {
	if (!C('DB_CHARSET')) {C('DB_CHARSET','utf8');}
//	$str = htmlspecialchars($str,ENT_COMPAT,C('DB_CHARSET'));
	$str =str_replace("\n",'<br>',$str);
	return $str;
}

/**
 * 将提交的数据进行反html格式编码
 * @param string $str	
 * @return string 
 */
function specDeConvertStr ($str) {
	if (!C('DB_CHARSET')) {C('DB_CHARSET','utf8');}
	$str = str_replace("<br>",'',$str);
	$str = html_entity_decode($str,ENT_COMPAT,C('DB_CHARSET'));
	return $str;
}



/**
     	 
 * 格式化数组(单个)
     
     * @access public
     * @Author 恺弘	   
     
 * @param array $info	数组
 * @param array $options	给参格式化的内容
     	 
 * @return string
 */
function _formatArray($info,$options=null){
	///判断格式化信息的有效性
	if (empty($info)) {		return $info;	}
	$list[0]	=	$info;
	$new_list	=	_formatList($list,$options,0); 	///格式化信息
	return $new_list['list'][0];
}

/**
 * 格式化数组(单个+组合明细)
 *
 * @param array $info
 * @param array $detailKey
 * @param array $options
 * @return array
 */
function _formatListRelation($info,$detailKey=array('detail'),$options=null){
	$list = _formatArray($info);
	if (is_array($detailKey)){
		foreach ((array)$detailKey as $key=>$value) {
			if (is_string($key)){}
			$detailList		= array();
			$detailList		= _formatList($list[$value],$options,1,'id');
			$list[$value]	= $detailList['list'];
			$list[$value.'_total']	= $detailList['total'];
		}
	}
	return $list;
}

/**
 * 格式化数组(单个+组合明细) 仅用于发票
 * @see _formatListRelation
 * @param array $info
 * @param string $detailKey
 * @param array $options
 * @return array
 */
function _formatListRelationForInvoice($info,$detailKey=array('detail'),$options=null){
	$list	= _formatListRelation($info,$detailKey,$options);
	///厂家来源配置为 独立厂家
	if(C('invoice.factory_from')==2){
		unset($list['factory_name']);
		unset($list['factory_iva']);
		$list	= _formatDdForInvoice('factory_id',$list,S('invoice_factory'));
	}
	///客户来源配置为 独立客户
	if(C('invoice.client_from')==2){
		unset($list['client_name']);
		unset($list['client_iva']);
		$list	= _formatDdForInvoice('client_id',$list,S('invoice_client'));
	}
	///公司来源配置为 独立公司
	if(C('invoice.company_from')==2){
		unset($list['basic_name']);
		$list	= _formatDdForInvoice('basic_id',$list,S('invoice_basic'));
	}
	///计算IVA
	$iva	= $list['iva']/100;
	foreach($detailKey as $_val){
		$dd	= S('invoice_product');
		if(!is_array($list[$_val])){
			continue;
		}
		foreach($list[$_val] as &$val){
			///配置为独立产品
			if(C('invoice.product_from')==2){
				unset($val['product_no']);
				unset($val['product_name']);
				$val	= _formatDdForInvoice('product_id',$val,$dd);
			}
			$total_money += $val['quantity']*$val['price']*(1-$val['discount']*0.01);
		}
		$list[$_val.'_total']['iva_cost']	= $iva*$total_money;
		$list[$_val.'_total']['total_cost']= round($total_money,2)+round($iva*$total_money,2);

		$format_money	= array('iva_cost','total_cost');
		$dml_money_leng	= array('iva_cost'=>'money_length','total_cost'=>'money_length');
		_format_money(&$format_money,&$list[$_val.'_total'],$dml_money_leng);
	}
	return $list;
}
/**
 * 格式化列表 仅用于发票
 * @see _formatList
 * @param array $info
 * @param array $options
 * @param int $sum_flag 判断是否需要统计合计 1 统计 0不统计
 * @param int $groupByKey 判断是否需要统计合计 1 统计 0不统计
 * @param array $expand
 * @return array
 */
function _formatListForInvoice($info,$options=null,$sum_flag=1,$groupByKey=null,$expand=array()){
	$info	= _formatList($info,$options,$sum_flag,$groupByKey,$expand);
	$cache_factory	= S('invoice_factory');
	$cache_client	= S('invoice_client');
	$cache_basic	= S('invoice_basic');
	$cache_product	= S('invoice_product');
	foreach($info['list'] as &$val){
		if(C('invoice.product_from')==2&&isset($val['product_id'])){
			unset($val['product_no']);
			unset($val['product_name']);
			$val	= _formatDdForInvoice('product_id',$val,$cache_product);
		}
		if(C('invoice.factory_from')==2&&isset($val['factory_id'])){
			unset($val['factory_name']);
			unset($val['factory_iva']);
			$val	= _formatDdForInvoice('factory_id',$val,$cache_factory);
		}
		if(C('invoice.client_from')==2&&isset($val['client_id'])){
			unset($val['client_name']);
			unset($val['client_iva']);
			$val	= _formatDdForInvoice('client_id',$val,$cache_client);
		}
		if(C('invoice.company_from')==2&&isset($val['basic_id'])){
			unset($val['basic_name']);
			$val	= _formatDdForInvoice('basic_id',$val,$cache_basic);
		}
		///		if(C('invoice.product_from')==2&&isset($val['product_id'])){
		///			$val	= _formatDdForInvoice('product_id',$val,$cache_product);
		///		}
	}
	return $info;

}
/**
 * 发票格式化取缓存
 * @param string $dd_id 缓存key
 * @param array $list
 * @param array $cache
 * @return array
 */
function _formatDdForInvoice($dd_id,$list,$cache=array()){
	$info	= $cache[$list[$dd_id]];
	foreach($info as $key=>$val){
		$list[$key]	= $val;
	}
	return $list;
}

/**
 	 
 * 格式化列表
 
 * @access public
 * @Author 恺弘	   
 
 * @param array $info	需要格式化的数组
 * @param array $options	给参格式化的内容
 * @param int $sum_flag		判断是否需要统计合计 1 统计 0不统计
 * @param int $groupByKey	判断是否需要统计合计 1 统计 0不统计
 * @param int $expand	扩展字段 详见 _formatListExpand 方法
 * 								$expand['sum_flag_key']		///合计的默认前缀
 * 								$expand['unset_sum_key_fields']	///合计的默认前缀
 * 								$expand['sum_group_by']	=	array('currency_id')	///根据不同币种或者对应的价进行合并 例如:currency_id 系统默认
 * 
 * 
 	 
 * @return string
 */
function _formatList($info,$optionsKey=null,$sum_flag=1,$groupByKey=null,$expand=array()){
	G('ddFmtTime');
	if (empty($info)) {		return $info;	}  ///判断格式化信息的有效性
	///初始化需要格式化的信息
	///		$option	=	C('_dd_config_'); ///获取格式化基础信息
	$expand['sum_group_by']	=	isset($expand['sum_group_by'])?$expand['sum_group_by']:array('currency_id');

	if(!empty($info))
	{
		$firstInfoArray	=	reset($info);
		///判断是否有记录第一次格式化的key的值 如果有直接读取内存中的 _format_first 历史的信息
		if ($optionsKey){
			///			echo '引用内存中的格式化信息';
			$_formatListCache	=	S('_formatList');
			if (empty($_formatListCache[$optionsKey])){
				///				echo '--本次第一次格式化,下次读取历史';
				$firstInfo						=	_format_first(&$firstInfoArray,&$sum_flag); 
				$info_cache_temp				=	$firstInfo['info_cache'];
				unset($firstInfo['info_cache']);
				$_formatListCache[$optionsKey]	=	$firstInfo;
				$firstInfo['info_cache']		=	$info_cache_temp;
				S('_formatList',$_formatListCache);
			}else{
				///				echo '--读取历史';
				$firstInfo						=	$_formatListCache[$optionsKey];
				///获取最新的 DD 信息
				_format_first_cache(&$firstInfo);
			}
		}else {
			$firstInfo	=	_format_first(&$firstInfoArray,&$sum_flag);
		}

		extract($firstInfo);
		if ($sum_flag){	$formatKey['count_product']=1; }///合计产品总数量

		///初始化内容
		$total_product 		= 0;	/// 产品总个数
		$total_product_temp = array();	/// 产品总个数记录缓存
		foreach ($info as $value) {
			///			if($i != 1) { ///只是开头运行 一次
			///				$firstInfo	=	_format_first(&$value,&$sum_flag);
			///				extract($firstInfo);
			///				if ($sum_flag){	$formatKey['count_product']=1; }///合计产品总数量
			///				$i	= 1;
			///			} /// end for if(empty($i))
			/** 开始处理 数据的 转化 * */
			foreach ((array)$formatKey as $forKey => $forVal) {   /// 先循环判断 获取 这次数据中有没 需要转换的字段
				switch ($forKey){
					case 'count_product':
						if ($value['product_id']>0){ _format_count_product(&$value,&$total_product_temp,&$total_product); } /// 根据规格统计明细中的产品数量
						break;
					case 'date':
						///如果 有需要转换的 日期 字段
						_format_date(&$info_date,&$value,&$dateModel);
						break;
					case 'money':
						///格式化金额
						_format_money(&$info_money,&$value,&$info_money_dml_leng);
						break;
					case 'dd':
						///格式化DD
						_format_dd(&$value,&$info_dd,&$define_dd,&$dd_split,&$info_cache);
						break;
					case 'const':
						///如果 有需要转换的 字典 字段
						_format_const(&$info_const,&$value,&$info_cache,&$info_const_relation);
						break;
					case 'sum':
						///合计字段
						_format_sum(&$value,&$sum,&$info_sum,$expand['sum_group_by']);
						break;
					case 'html':
						///格式化 备注等信息
						_format_html(&$info_html,&$value);
						break;
				}
			}
			///按照$groupByKey的值给数组
			if (isset($value[$groupByKey])){
				$rs['list'][$value[$groupByKey]]	= $value;
			}else {
				$rs['list'][]	= $value;
			}
		} /// end for foreach ($info as $value)
	} /// end for if(!empty($info))
	///合计
	if ($sum_flag && is_array($sum)) {
		_format_total(&$info_sum,&$sum,&$rs,&$total_product,$info_money_dml_leng,$expand['sum_group_by']);
	}///格式化合计字段内容
	G('endDdFmtTime');
	unset($info,$info_cache,$sum); ///内存注销变量 ///内存注销变量 ///内存注销变量 
	return $rs;	///返回格式化完的数组信息
}


/**
 * 根据object_id 与 object_type
 * 返回相对应的链接
 *
 * @param array $list
 * @param string $list_key
 * @return array
 */
function _addFlowLink($list,$Lkey='list'){
	if (!is_array($list)){	return $list; }
	$linkModel	=	D('AbsStat');
	foreach ($list[$Lkey] as $key=> &$row) {  $linkModel->objectTypeCommentSubsidiary(&$row); }
	return $list;
}

/**
 * _format_first_cache
 *
 * @param array $firstInfo
 */
function _format_first_cache(&$firstInfo){
	unset($firstInfo['info_cache']);
	foreach ((array)$firstInfo['info_dd'] as $key => $value) {   /// 先循环判断 获取 这次数据中有没 需要转换的字段
		$dd_name							=	$firstInfo['define_dd'][$value];
		$firstInfo['info_cache'][$dd_name]	=	S($dd_name);
	}
	foreach ((array)$firstInfo['info_const_relation'] as $key => $value) {   /// 先循环判断 获取 这次数据中有没 需要转换的字段
		$firstInfo['info_cache'][$key]	=	C($value);
	}
}

/**
 * _format_first
 *
 * @param array $value
 * @param array $sum_flag
 * @return array
 */
function _format_first(&$value,&$sum_flag){
	$option 			= include(THINK_PATH.'Conf/dd_config.php');
	$define_dd			= $option['FORMAT_DD']; ///读取需要 字典格式化的字段
	$define_html		= $option['FORMAT_HTML'];///读取需要 转html 的字段
	$define_date		= $option['FORMAT_DATE'];///读取需要 日期格式化的字段
	$define_money		= $option['FORMAT_MONEY']; ///读取需要 金钱格式化的字段
	$define_const		= $option['FORMAT_CONST']; ///读取需要 常量格式化的字段
	$formatKey			= array();///需要格式化的内容
	///求和统计
	if ($sum_flag) {
		$define_sum		= 	$option['FORMAT_SUM'];    ///读取需要 累加的字段 即是合计字段
	}
	$dml			=	array(	1=>'money_length',	2=>'price_length',	3=>'int_length',	4=>'int',5=>'cube_length'	);	///数字小数位数 金额=>1,单价=>2,数量=>3

	$dd_split_quantity		= 0;	///字段中切割缓存的个数
	$dd_splits				= S('Dd_split');	///被切割字典类型
	$dd_split				= array_keys($dd_splits);

	foreach ($value as $key => $value_list) {   /// 先循环判断 获取 这次数据中有没 需要转换的字段
		if(in_array($key,$define_date)) {  ///判断是否 有需要转换的 日期 字段
			$info_date_count++;
			if ($info_date_count<2) {///初始化载入日期控件
				import("ORG.Util.Date");
				$dateModel				= new Date();
				$reInfo['dateModel']	= $dateModel;
			}
			$formatKey['date']=1;
			$reInfo['info_date'][]			=	$key;
			$reInfo['info_date_count']		=	$info_date_count;
			continue;
		}
		if(in_array($key,array_keys($define_dd))) {
			///判断是否 有需要转换的 字典 字段
			$info_cache[$define_dd[$key]]	=	S($define_dd[$key]);
			$reInfo['info_dd'][]			=	$key;
			$formatKey['dd']=1;
			continue;
		}
		if(in_array($key,array_keys($define_const))) {
			///判断是否 有需要转换的 字典 字段
			$info_const[]	= $key;
			$info_cache[$key]	 								=	C(($define_const[$key]));
//			$info_cache[strtolower($define_const[$key])]	 	=	C(($define_const[$key]));
			$reInfo['info_const'][]								=	$key;
			$reInfo['info_const_relation'][$key]				=	$define_const[$key];
			$formatKey['const']=1;
			continue;
		}
		if(in_array($key,array_keys($define_money))) {
			///判断是否 有需要转换的 金钱 字段， 因为金额可能要累加 合计 所以没有 continue;
			$reInfo['info_money'][]					=	$key;
			$reInfo['info_money_dml_leng'][$key]	=	$dml[$define_money[$key]];///数字小数位数 金额=>1,单价=>2,数量=>3
			$formatKey['money']=1;
		}
		///求和
		if($sum_flag && in_array($key,array_keys($define_sum))) {  ///判断是否是 累加的字段 即是合计字段
			$formatKey['sum']=1;
			$reInfo['info_sum'][]				=	$key;
			$reInfo['info_sum_dml'][]			=	$dml[$define_sum[$key]];
			continue;
		}
		if(in_array($key,$define_html)) {  ///判断是否是 转html 的字段
			$reInfo['info_html'][]	= $key;
			$formatKey['html']=1;
			continue;
		}
	}


	if (is_array($info_cache)){ $reInfo['info_cache']	=	$info_cache;}
	$reInfo['dml']					=	$dml;
	$reInfo['formatKey']			=	$formatKey;
	$reInfo['define_dd']			=	$define_dd;
	$reInfo['dd_split_quantity']	=	$dd_split_quantity;
	$reInfo['dd_splits']			=	$dd_splits;
	$reInfo['dd_split']				=	$dd_split;
	return $reInfo;
}

/**
 * 格式化金额
 *
 * @param array $info_money
 * @param double $value
 * @param int $info_money_dml_leng
 */
function _format_money(&$info_money,&$value,&$info_money_dml_leng){
	///如果 有需要转换的 金钱 字段
	foreach ($info_money as $info_money_key=>$value_money) {
		///		$value['ltc_dml_'.$value_money]		= 'class="t_right"';
		$value['dml_'.$value_money]			= moneyFormat($value[$value_money],0,C($info_money_dml_leng[$value_money]));
		$value['edml_'.$value_money]		= moneyFormat($value[$value_money],0,C($info_money_dml_leng[$value_money]),false);
	}
}

/**
 * 如果 有需要转html 字段
 * 例如备注等
 *
 * @param array $info_html
 * @param array $value
 */ 
function _format_html(&$info_html,&$value){
	///如果 有需要转html 字段
	foreach ($info_html as $value_html) {
		$value['edit_'.$value_html]	= ($value[$value_html]);
		$value[$value_html]			= specConvertStr($value[$value_html]);
	}
}

/**
 * 格式化指定类型字典
 *
 * @param array $info_const
 * @param array $value
 * @param array $info_cache
 * @param array $define_const
 */
function _format_const(&$info_const,&$value,&$info_cache,&$info_const_relation){
	if(!empty($info_const)) {
		foreach ($info_const as $value_dd) {  
			$dd_array			=&$info_cache[$value_dd][$value[$value_dd]];  ///因为 优先级别，所以这里先 定义，然后再匹配
			if (!empty($dd_array)){
				$value['dd_'.$value_dd]	=	$dd_array;
			}
		}
	}
}

/**
 * 根据规格统计明细中的产品数量
 *
 * @param array $value
 * @param array $total_product_temp
 * @param array $total_product
 */
function _format_count_product(&$value,&$total_product_temp,&$total_product){
	if ($value['product_id']>0 && $value['capability'] && !isset($total_product_temp[$value['product_id']])){
		$total_product_temp[$value['product_id']] = true;
		$total_product +=1;
	}
}

/**
 * 格式化日期
 *
 * @param array $info_date
 * @param array $value
 */
function _format_date(&$info_date,&$value,&$dateModel){
	foreach ($info_date as $value_date) {
		if (empty($value[$value_date])) {continue;}
		$value['fmd_'.$value_date]		= $dateModel->getFormat($value[$value_date]);
		///		$value['ltc_fmd_'.$value_date]	= 'class="t_center"';
	}
}

/**
 * 格式化DD数组
 *
 * @param array $info
 * @param array $define_dd
 * @param array $dd_split
 * @param array $info_cache
 */
function _format_dd(&$value,&$info_dd,&$define_dd,&$dd_split,&$info_cache){ 
	
	foreach ($info_dd as $value_dd) { 
		///判断是否是切割的缓存字典
		if (in_array($define_dd[$value_dd],$dd_split) && $value[$value_dd]>0) { 
			///判断是否已存在切割过的缓存字典
			$split_no		=	intval($value[$value_dd]/5000);
			$split_name		=	$define_dd[$value_dd].'_'.$split_no;
			///判断切割过的ID是否已经取过切割后的字典
			if (empty($info_cache[$split_name])) {
				$info_cache[$split_name] = S($split_name);
			}
			$dd_array	=&$info_cache[$split_name]; 
		}else{
			$dd_array	=&$info_cache[$define_dd[$value_dd]];  ///因为 优先级别，所以这里先 定义，然后再匹配
		}
		if (is_array($dd_array[$value[$value_dd]])){
			$value	=	array_merge($value,$dd_array[$value[$value_dd]]) ;
		}
	}
}

/**
 * 格式化统计
 *
 * @param array $info_sum 
 * @param array $sum
 * @param array $rs
 * @param array $total_product
 */
function _format_total(&$info_sum,&$sum,&$rs,&$total_product,$info_money_dml_leng,$groupBy){

	///格式化合计字段内容
	foreach ((array)$info_sum as $key=>$row) {
		$sum[$row]	= $sum[$row];
		$sum['dml_'.$row]	= moneyFormat($sum[$row],0,C($info_money_dml_leng[$row]));
	}
	$currencyDd	=	S('currency');
	///格式化各个币种的合计金额
	foreach ((array)$groupBy as $key=>$row) {
		if ($row=='currency_id'){
			foreach ((array)$sum[$row.'_sum'] as $sumk =>$sumr) {
				$sum['dml_'.$row.'_'.strtolower($currencyDd[$sumk]['currency_no'])]	= moneyFormat($sumr,0,C('money_length'));
			}
		}else{
			foreach ((array)$sum[$row.'_sum'] as $sumk =>$sumr) {
				foreach ((array)$sumr as $sumrk =>$sumrv) {
					$sum['dml_'.$row.'_'.strtolower($currencyDd[$sumk]['currency_no']).'_'.$sumrk]	= moneyFormat($sumrv,0,C('money_length'));
				}
			}
		}
	}
	$sum['total_product'] = $total_product;
	$rs['total']	= $sum;
}


/**
 * 格式化合计部分(如果 有需要累加的字段  即是合计字段 )
 *
 * @param array $value
 * @param array $sum
 * @param array $info_sum
 */
function _format_sum(&$value,&$sum,&$info_sum,$groupBy=array('currency_id')){
	foreach ((array)$groupBy as $groupByValue) {
		$$groupByValue	=	isset($value[$groupByValue])?$value[$groupByValue]:1;
	}
	///判断是否需要合计
	foreach ((array)$info_sum as $value_sum) {
		$sum[$value_sum]	+= $value[$value_sum];
		foreach ((array)$groupBy as $groupByValue) {
			if ($groupByValue=='currency_id'){
				$sum[$groupByValue.'_sum'][$$groupByValue]	+= $value[$value_sum];
			}else{
				$sum[$groupByValue.'_sum'][$currency_id][$$groupByValue]	+= $value[$value_sum];
			}
		}
	}
}


/**
 * 格式化数组
 *
 * @param array $data
 * @param string  $key 多个用","分隔，最多两个 返回数组的key
 * @param string  $value_key  多个用","分隔   返回数组的数据项key
 * @author 邹燕娟
 */
function formatArray($data, $key = '', $value_key = '') {
	if (!is_array($data) || empty ($data)) {
		return false;
	}
	if ($value_key && strpos(',')) {
		$value_key = explode(",", $value_key);
	}
	if (!strstr($key,",")) { /// key 为字符串
		foreach ($data as $k => $list) {
			$key_0 = $list[$key] ; /// 数组的键值
			if (!empty($value_key) && count($value_key) > 1) {
				foreach ($value_key as $v_key){
					$new_list[$key_0][$v_key] = $list[$v_key];
				}
			}elseif (!empty($value_key) && count($value_key)==1){
				$new_list[$key_0] = $list[$value_key];
			}
			else {
				$new_list[$key_0] = $list;
			}
		}
	} else {	/// key 为数组
		$key = explode(",",$key) ;
		foreach ($data as $k => $list) {
			$key_0 = $list[$key[0]]; /// 数组的键值
			$key_1 = $list[$key[1]]; /// 数组的键值
			if (!empty($value_key) && count($value_key) > 1) {
				foreach ($value_key as $v_key){
					$new_list[$key_0][$key_1][$v_key] = $list[$v_key];
				}
			} elseif (!empty($value_key) && count($value_key)==1){
				$new_list[$key_0] = $list[$value_key];
			}
			else {
				$new_list[$key_0][$key_1] = $list;
			}
		}
	}
	return $new_list;
}

/**
 * 删除空值或0
 *
 * @param string $str
 * @return $str
 */
function dml($str,$price_foramt=null){
	if ($price_foramt) {
		$str = moneyFormat($str,0,C('PRICE_LENGTH'));
	}else {
		$str = trim($str);
	}
	if (empty($str) || floatval($str)==0 || $str=='NaN') {
		return ;
	}
	return $str;
}


/**
 * 更新字典缓存信息
 *
 * @param  int $id	 缓存索引值
 * @param  int $table_id 
 * @param string $where 查询条件
 * @param  int $time
 * @return bool
 */
function cacheDd($id,$table_id,$where=null,$time=0){
	$id			=	intval($id);
	if ($id<=0) { return false;	}
//	$Dd			=	S('Dd');
	///如果字典Dd不存在重新生成
	if (!is_array($Dd)){
		$Dd			=	createCacheDd();	
	}  
	///	if (!is_array($Dd)) { createCacheDd();	$Dd	=	S('Dd');}
	$Dd			=	$Dd[$id]; 
	if (!is_array($Dd)) { return false;	}
	///字段
	$dd_value	=	explode(',',$Dd['dd_value']);
	$count		=	count($dd_value);
	if ($count<=0) { return false;	}
	$model		=	M($Dd['dd_table']);
	empty($where)	&&	$where=' 1 ';
	!empty($Dd['dd_where']) && $where		.=' and '.$Dd['dd_where'];
	///需要进行拆分 
	if ($Dd['dd_split']==2) {
		///数组最大数量
//		$max_limit		= $Dd['dd_split_quantity'];
		$max_limit		= 5000; 
		///单独更新拆分后的一个数组
		if ($table_id>0) {
			$split_count	=	intval($table_id/$max_limit);
			$Dd['dd_name'].'_'.$split_count;
			$limit 	='  and  id>'.($split_count)*$max_limit.' and id<='.(($split_count+1)*$max_limit).' ';
			PushCacheDd(&$model,$where.$limit,&$Dd,&$count,&$dd_value,$Dd['dd_name'].'_'.$split_count,true,$limit,$time);
		}else{
			$sun_record = $model->where($where)->max('id'); ///总个数
			///拆分后的个数
			$split_count	=	intval($sun_record/$max_limit);
			for ($i = 0; $i <= $split_count; $i++) {
				if ($i==0) {
					$limit 	='  and  id<='.$max_limit;
				}else{
					$limit 	='  and  id>'.($i)*$max_limit.' and id<='.(($i+1)*$max_limit).' ';
				}
				PushCacheDd(&$model,$where.$limit,&$Dd,&$count,&$dd_value,$Dd['dd_name'].'_'.($i),true);
			}
		}
	}else{
		$sun_record = $model->where($where)->count(); ///总个数
		if ($sun_record>10000) {ini_set('memory_limit', '512M');}
		PushCacheDd(&$model,&$where,&$Dd,&$count,&$dd_value,'','','',$time);
		return true;
	}
	return ;
}


/**
 * 把字典压缩到内存
 *
 */
function createCacheDd(){
	$dd_list	=	M('Dd')->select();
	$dd_split	=	array();
	foreach ((array)$dd_list as $key=>$row) { 
		$dd[$row['id']]		=	$row;
		if ($row['dd_split']==2) {
//			$dd_split[$row['dd_name']]	=	$row['dd_split_quantity'];
			$dd_split[$row['dd_name']]	=	$row['id'];
		}
	}  
	///压入内存
	S('Dd',$dd);
	///需要切割的字典名称
	S('Dd_split',$dd_split);
	return $dd;
}


/**
 * 把信息压入内存
 *
 * @param object $model
 * @param string $where
 * @param array $Dd
 * @param int $count
 * @param string $dd_value
 * @param string $dd_name
 * @param bool $split
 * @param array $limit
 */
function PushCacheDd($model,$where,$Dd,$count,$dd_value,$dd_name='',$split=false,$limit=array(),$time){
	$Dd['dd_key']	=	trim($Dd['dd_key']);
	if ($split) {
		$list		=	$model->field($Dd['dd_key'].','.$Dd['dd_value'])->where($where)->order($Dd['dd_key'])->select();
	}else{
		$list		=	$model->field($Dd['dd_key'].','.$Dd['dd_value'])->where($where)
		->order($Dd['dd_key'])->select();
	} 
	///	if ($count==1) {///一维数组
	///		echo '<pre>';
	///		echo print_r($list);
	///		echo '<pre>';
	///
	///		exit;
	///		foreach ((array)$list as $key=>$row) {
	///			$rs[$row[$Dd['dd_key']]]		=	array($dd_value[0]=>$row[$dd_value[0]]);
	///		}
	///	}else{
	///多维数组
	foreach ((array)$list as $key=>$row) {
		$info	=	array();
		///			foreach ((array)$dd_value as $key2=>$row2) {
		///				$info[$row2]		=	$row[$row2];
		///			}
		$id			=	$row[$Dd['dd_key']];
		unset($row[$Dd['dd_key']]);
		$rs[$id]	=	$row;
		unset($info);
	}
	///	}
	///判断数组是否存在
	if (is_array($rs)) {
		///字典名称
		$dd_name	= 	empty($dd_name)?$Dd['dd_name']:$dd_name;
		S($dd_name,$rs,$time);
		unset($rs);
	}
	return ;
}

/**
 * 对pathinfo格式字条串转数组
 *
 * @param array $pathinfo
 * @return array
 */
function parsePathinfo($pathinfo){
	$var = array();
	$paths = explode('/',$_POST['id']);
	preg_replace('@(\w+)/([^\/]+)@e', '$var[\'\\1\']="\\2";', implode('/',$paths));
	return $var;
}
/**
     
     * 获取页面传递来的查询条件
     
     * @access public
     * @Author 恺弘
     
     * @return $default_where 默认的where条件
     * @return $default 第一次载入附加的where条件
     
     */	
function _search($default_where=null,$default=null){
	!empty($default_where)	&&	$where	=	' and '.$default_where;
	return getWhere($_POST,$default).$where;
}

/**
 * 简化的_search传递什么查询什么
 *
 * @param array $array
 * @return array
 */
function _search_array($array){
	return getWhere($array);
}

/**
 * 特殊的get的URL整理成需要查询的post格式
 * 
 * 例子: 	$get['sp_query_paid_date']	= 'abc';
			$get['sp_query_paid_date2']	= '123';
	结果:
		Array
		(
		    [query] => Array
		        (
		            [paid_date] => abc
		            [paid_date2] => 123
		        )
		
		) 
 * @param array $list
 */
function _getSpecialUrl($get){
	foreach ($get as $key => $value) {
		if(substr($key,0,3) == 'sp_')
		{
			$array	=	explode('_',$key);
			if (count($array)>2){
				$name	=	str_replace($array[0].'_'.$array[1].'_','',$key);
				if (strpos($name,'__')) {
					$name	= str_replace('__','.',$name);
				}
				$info[$array[1]][$name]	= $value ;
			}
		}
	}
	return	$info;
}

/**
 * 合并GET值至POST，同时返回查询条件
 *
 * @return  string
 */
function _getMergePostReturnWhere(){
	$array	= _getSpecialUrl($_GET);
	$where	= _search_array($array);
	if (is_array($array)){
		$_POST	=	array_merge($array,$_POST);
	}
	return $where;
}

/**
 * 根据数组 调用不同条件，提取 SQL语句的 WHERE条件
 *
 * @param array $info
 * @return string
 */
function getWhere($info,$default){
	global $_search_form;
	$_POST['ac_search'] && $_search_form = true;
	/// 合并default_post属性值与实际的POST值，实际POST优先级高
	if (is_array($default)) {
		$_POST = array_merge($default,$info);
	}
	$where	= ' 1 ';               ///WHERE 的初始化
	if(count($default['query']) > 0)    ///where的默认条件
	{
		foreach ($default['query'] as $fieldName => &$fieldValue) {

			if (!empty($fieldName) && $fieldValue!=NULL &&	empty($info['query'][$fieldName]) && !isset($info['query'][$fieldName]))
			{
				$fieldValue	= trim($fieldValue);
				if (empty($fieldValue)) {	continue;	}
				///					empty($fieldValue)	&& $fieldValue = 0;
				$where 	.= ' and '.$fieldName.'="'.$fieldValue.'" ';
				///POST转换将.替换成_
				if (strpos($fieldName,'.')) {
					$new_key = str_replace('.','_',$fieldName);
					unset($default['query'][$new_key]);
					$_POST['query'][$new_key]	=	$fieldValue;
				}
			}
		}
	}
	if(count($info['query']) > 0)    ///一般 WHERE条件的提取
	{
		foreach ($info['query'] as $fieldName => &$fieldValue) {
			if (is_array($fieldValue)){ continue; }
			if ($fieldValue!=NULL && (!empty($fieldValue))){
				if($fieldValue=='-2') continue;
				$where 	.= ' and '.$fieldName.'="'.$fieldValue.'" ';
				///POST转换将.替换成_
				if (strpos($fieldName,'.')) {
					$new_key = str_replace('.','_',$fieldName);
					unset($info['query'][$new_key]);
					$_POST['query'][$new_key]	=	$fieldValue;
				}
			}
		}
	}
	if(count($info['morethan']) > 0)    ///大于等于
	{
		foreach ($info['morethan'] as $fieldName => &$fieldValue) {
			if (!empty($fieldName) && $fieldValue!=NULL)
			{
				$fieldValue	= trim($fieldValue);
				empty($fieldValue)	&& $fieldValue = 0;
				$where 	.= ' and '.$fieldName.'>="'.$fieldValue.'" ';
			}
		}
	}
	if(count($info['like']) > 0)   ///LIKE 语句的提取
	{
		foreach ($info['like'] as $fieldName => &$fieldValue) {
			if (!empty($fieldName) && $fieldValue!=null)
			{
				$where 	.= ' and '.$fieldName.' like "%'.$fieldValue.'%" ';
				///POST转换将.替换成_
				if (strpos($fieldName,'.')) {
					$new_key = str_replace('.','_',$fieldName);
					unset($info['query'][$new_key]);
					$_POST['like'][$new_key]	=	$fieldValue;
				}
			}
		}
	}
	///多个日期查询需要在页面中增加 date_key 几组日期的数量
	if ($info['date_key']>0) {
		for ($i = 1; $i <= $info['date_key']; $i++) {
			$info_key	 =	$i>1?$i:'';
			$where		.=	_getWhereDate($info,'date'.$info_key);
		}
	}else{
		$where	.=	_getWhereDate($info);
	}
	return $where;
}
/**
 * 格式化日期格式，入库时格式化为：0000-00-00 显示时格式化为 00/00/00
 * @param string $dateTime 要格式化的时间
 * @param string $formatTo 将时间格式化为指定格式：date (Y-m-d) outdate 根据当格式转出 ,其它格式见:MyDate->format方法
 * @return string 
 */ 
function formatDate($dateTime,$formatTo='date'){
	///日期格式判断
	if(empty($dateTime) || $dateTime=='0000-00-00' || $dateTime=='0000-00-00 00:00:00'){
		return '';
	}
	if (strpos($dateTime,'/')){
		$arr_dateTime	=	explode(' ', $dateTime);
		$date_array = split('/',$arr_dateTime[0]);
		$year  		= $date_array[2];
		$month 		= $date_array[1];
		$date  		= $date_array[0];
		$dateTime 	= '20'.$year.'-'.$month.'-'.$date;
		$arr_dateTime[1] && $dateTime.= ' '.$arr_dateTime[1];
	}
	switch ($formatTo){
		case 'date':	///导入数据库
		$returnDate	=	$dateTime;
		break;
		case 'vf_date': /// 表单验证中的格式转换
		$dateTime	= substr($dateTime,0,10);
		$returnDate	= $dateTime;///.'-'.$dateTime[1].'-'.substr($dateTime[2],0,2);
		break;
		case 'mg_date': /// 表单验证中的格式转换
		$dateTime	= substr($dateTime,0,10);
		$returnDate	= $dateTime;///.'-'.$dateTime[1].'-'.substr($dateTime[2],0,2);
		$date_array = split('-',$returnDate);
		$returnDate	= substr(join('',$date_array),2,8);
		break;
		case 'outdate':	///导出日期格式化
		import("ORG.Util.Date");
		$dateModel	=	new Date();
		$returnDate	=	$dateModel->getFormat($dateTime);
		break;
	}
	return $returnDate;
}

/**
 * 多个日期查询
 *
 * @param array $info
 * @param string $info_key 日期下标KEY值
 * @return string
 */
function _getWhereDate($info,$info_key='date'){
	$where	=	'';
	if(count($info[$info_key]) > 0)   ///日期 语句的提取
	{
		foreach ($info[$info_key] as $fieldName => &$fieldValue) {
			if (!empty($fieldName) && $fieldValue!=null)
			{
				$fieldValue		= formatDate($fieldValue,'date'); ///对日期格式化 存入数据库
				if (strpos($fieldName,'.')) {
					///POST转换将.替换成_
					$_POST['date'][str_replace('.','_',$fieldName)]	=	$fieldValue;
					$exp_date	=	explode('.',$fieldName);
					$fieldName	=	$exp_date[1];
					$fix_date	=	$exp_date[0].'.';
				}
				if(substr($fieldName,0,9) == 'needdate_')
				{
					$fieldName	= substr($fieldName,9);
					$needdate	= 1;
				}

				if(substr($fieldName,0,5) == 'from_')
				{
					$fileds		= $needdate	?	'date('.substr($fieldName,5).')'	:	substr($fieldName,5);
					$date_from	= $fieldValue;
				}
				else if(substr($fieldName,0,3) == 'to_')
				{
					$fileds		= $needdate	?	'date('.substr($fieldName,3).')'	:	substr($fieldName,3);
					$date_to	= $fieldValue;
				}
				else if(substr($fieldName,0,3) == 'mt_')   ///大于 该日期段
				{
					$fileds		= $needdate	?	'date('.substr($fieldName,3).')'	:	substr($fieldName,3);
					$where 		.= ' and date('.$fileds.')>="'.$fieldValue.'" ';
				}
				else if(substr($fieldName,0,4) == 'mtt_')   ///大于 该日期段
				{
					$fileds		= $needdate	?	'date('.substr($fieldName,4).')'	:	substr($fieldName,4);
					$where 		.= ' and date('.$fileds.')>"'.$fieldValue.'" ';
				}
				else if(substr($fieldName,0,3) == 'lt_')   ///小于 该日期段
				{
					$fileds		= $needdate	?	'date('.substr($fieldName,3).')'	:	substr($fieldName,3);
					$where 		.= ' and date('.$fileds.')<="'.$fieldValue.'" ';
				}
				else if(substr($fieldName,0,4) == 'ltt_')   ///小于 该日期段
				{
					$fileds		= $needdate	?	'date('.substr($fieldName,4).')'	:	substr($fieldName,4);
					$where 		.= ' and date('.$fileds.')<"'.$fieldValue.'" ';
				}
				else {
					$where 		.= ' and date('.$fieldName.')="'.$fieldValue.'" ';
				}
			}
		}
	}
	if($date_from  || $date_to)
	{
		if (MODULE_NAME!='Orders' && in_array($fileds,array('order_date','delivery_date','pre_delivery_date','return_order_date'))){
			$fileds	=	$fileds.'_format';
		}
		if($date_from && $date_to)   ///日期都存在
		{
			$where			.= ' and '.$fix_date.$fileds.'>="'.$date_from.'" and '.$fix_date.$fileds.'<="'.$date_to.'" ';
		}
		else
		{
			$date_from	?	$date	= $date_from : ($date_to	?	$date	= $date_to : $date = '-1');
			$where			.= ' and '.$fix_date.$fileds.'="'.$date.'" ';
		}
	}
	return $where;
}


/**
 * 取随机数
 *
 * @param int $length 需要返回的随机数长度
 * @return string
 */
function getRands($length=8){
	$str = 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,';
	$str .= 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,';
	$str .= '0,1,2,3,4,5,6,7,8,9';
	$all=explode(",",$str);
	$randy = '';
	for($i=0;$i<$length;$i++){
		$randy		 = rand(0,61);
		$randStr	.= $all[$randy];
	}
	return $randStr;
}

/**
 * 通过scoket方式运程访问文件
 *
 * @param string $url  请求址
 * @param int $limit  每次读取值大小
 * @param String $post  POST参数
 * @param String $cookie  cookie信息
 * @param  bool $bysocket 
 * @param String $ip  远程地址
 * @param int $timeout  超时时间
 * @param bool $block  0是非阻塞，1是阻塞
 * @return string
 */
function uc_fopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
	$return = '';
	$matches = parse_url($url);
	!isset($matches['host']) && $matches['host'] = '';
	!isset($matches['path']) && $matches['path'] = '';
	!isset($matches['query']) && $matches['query'] = '';
	!isset($matches['port']) && $matches['port'] = '';
	$host = $matches['host'];
	$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
	$port = !empty($matches['port']) ? $matches['port'] : 80;
	if($post) {
		$out = "POST $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		///$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= 'Content-Length: '.strlen($post)."\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cache-Control: no-cache\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
		$out .= $post;
	} else {
		$out = "GET $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		///$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
	}
	$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
	if(!$fp) {
		return '';///note $errstr : $errno \r\n
	} else {
		stream_set_blocking($fp, $block);
		stream_set_timeout($fp, $timeout);
		@fwrite($fp, $out);
		$status = stream_get_meta_data($fp);
		if(!$status['timed_out']) {
			while (!feof($fp)) {
				if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
					break;
				}
			}

			$stop = false;
			while(!feof($fp) && !$stop) {
				$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
				$return .= $data;
				if($limit) {
					$limit -= strlen($data);
					$stop = $limit <= 0;
				}
			}
		}
		@fclose($fp);
		return $return;
	}
}

/**
 * 循环创建目录
 *
 * @param  string $dir
 * @param  int $mode
 * @return  bool
 */
function mk_dir($dir, $mode = 0777)
{
	if (is_dir($dir) || @mkdir($dir,$mode)) return true;
	if (!mk_dir(dirname($dir),$mode)) return false;
	return @mkdir($dir,$mode);
}


/**
 * 自动转换字符集 支持数组转换
 *
 * @param string $fContents
 * @param  string $from
 * @param  string $to
 * @return  string
 */
function auto_charset($fContents,$from='gbk',$to='utf-8'){
	$from   =  strtoupper($from)=='UTF8'? 'utf-8':$from;
	$to       =  strtoupper($to)=='UTF8'? 'utf-8':$to;
	if( strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents)) ){
		///如果编码相同或者非字符串标量则不转换
		return $fContents;
	}
	if(is_string($fContents) ) {
		if(function_exists('mb_convert_encoding')){
			return mb_convert_encoding ($fContents, $to, $from);
		}elseif(function_exists('iconv')){
			return iconv($from,$to,$fContents);
		}else{
			return $fContents;
		}
	}
	elseif(is_array($fContents)){
		foreach ( $fContents as $key => $val ) {
			$_key =     auto_charset($key,$from,$to);
			$fContents[$_key] = auto_charset($val,$from,$to);
			if($key != $_key )
			unset($fContents[$key]);
		}
		return $fContents;
	}
	else{
		return $fContents;
	}
}

function getLimit($count){
	$limit = _page($count);
	return _limit($limit);
}

/**
 * 分页信息数组
 *
 * @param array $limit
 * @return  string
 */
function _limit($limit){
	if(empty($limit)) return ;
	return ' limit '.$limit['firstRow'].','.$limit['listRows'];
}
/**
 * 分页
 *
 * @param int $count
 * @return array
 */
function _page($count,$listRows=null){
	if ($count > 0) {
		import("ORG.Util.Page");
		///实例化分页对象
		$p = new Page ( $count, $listRows );
		///模型对象$options条件赋值

		///			foreach ((array)$options as $key=>$row) {
		///				if (in_array($key,array('sortBy'))) {continue;}
		///				$model->$key($row);
		///			}

		///获取列表信息->分页查询数据
		///			$voList = $model->order( "" . $order . " " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
		$limit['firstRow']	=	$p->firstRow;
		$limit['listRows']	=	$p->listRows;
		///分页显示
		$page = $p->show ();
		///列表排序显示
		$sortImg 	= $sort; ///排序图标
		$sortAlt 	= $sort == 'desc' ? L('SORT_ASC') : L('SORT_DESC'); ///排序提示
		$sort 		= $sort == 'desc' ? 1 : 0; ///排序方式
		///			$assign_array = array();
		///			$assign_array = $voList;
		///模板赋值显示
		$view       = Think::instance('View');
		$view->assign ( 'sort', $sort );
		$view->assign ( 'order', $order );
		$view->assign ( 'sortType', $sortAlt );
		$view->assign ( "page", $page );///页码

		///记录本次POST的值与SESSION
		/*import ( "@.ORG.Session" );
		$Session 		= 	new Session();   ///初始化分页对象
		$Session->setLocal('post_'.MODULE_NAME.'_'.ACTION_NAME,$_POST); ///设置本地化Session癿值
		$Session->set('_output_sql_',$model->getLastSql()); */
	}else{
		return false;
	}
	return	$limit;
}

/**
      
     * 根据表单生成查询条件
     * 进行列表过滤
      
     * @access protected
      
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
      
     * @return void
      
     * @throws ThinkExecption
      
     */
function _list(&$model,&$options) {
	if (ACTION_NAME=='index' && empty($_GET['p'])) {
		global $_search_form;
		///			if (!getShowData() && !$_search_form) { return array();}
	}
	///初始化$model
	if (!is_object($model)) {
		///获取当前Action名称
		$name = $this->getActionName();
		///获取当前模型
		$model 	= D($name);
	}
	extract($options);
	$is_rights	=	$model->_is_rights==false?0:1;
	$asc	=	!empty($asc)?$asc:$model->_asc;
	$asc	=	$asc	==true?true:false;
	$_child	=	$_child	==true?true:false;
	$sortBy	=	!empty($sortBy)?$sortBy:$model->_sortBy;
	///排序字段 默认为主键名
	if (isset ( $_REQUEST ['_order'] )) {
		$order = $_REQUEST ['_order'];
	} else {
		$order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
	}
	///排序方式默认按照倒序排列
	///接受 sost参数 0 表示倒序 非0都 表示正序
	if (isset ( $_REQUEST ['_sort'] )) {
		$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
	} else {
		$sort = $asc ? 'asc' : 'desc';
	}

	///取得满足条件的记录数
	$group	=	0;
	///判断是简单求列还是复杂求列整理get_count的个数
	foreach ((array)$options as $key=>$row) {
		if (in_array($key,array('table','where','having','group','distinct'))) {
			if (in_array($key,array('having','group'))) {
				$group++;
				continue;
			}
			$model->$key($row);
		}
	}
	///获取列表的总个数
	if ($group>0) {
		$count	=	$model->count(' DISTINCT '.$options['group']);
		///			$count	=	1;
	}else{
		$count	=	$model->count(1);
	}
	///		echo '<br>';  echo '<br>';  echo '<br>';
	///		echo $model->getLastSql();
	///		echo '<br>';
	///		exit;
	if ($count > 0) {
		import("ORG.Util.Page");
		///			import ( "@.ORG.Page" );
		///创建分页对象
		$listRows=	(! empty ( $_REQUEST ['listRows'] ))?$_REQUEST ['listRows']:'';
		///实例化分页对象
		$p = new Page ( $count, $listRows );
		///模型对象$options条件赋值

		foreach ((array)$options as $key=>$row) {
			if (in_array($key,array('sortBy'))) {continue;}
			$model->$key($row);
		}

		///获取列表信息->分页查询数据
		$voList = $model->order( "" . $order . " " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();

		///分页显示
		$page = $p->show ();
		///列表排序显示
		$sortImg = $sort; ///排序图标
		$sortAlt = $sort == 'desc' ? L('SORT_ASC') : L('SORT_DESC'); ///排序提示
		$sort = $sort == 'desc' ? 1 : 0; ///排序方式
		$assign_array = array();
		$assign_array = $voList;
		///模板赋值显示
		$view       = Think::instance('View');
		$view->assign ( 'sort', $sort );
		$view->assign ( 'order', $order );
		$view->assign ( 'sortType', $sortAlt );
		$view->assign ( "page", $page );///页码

		///记录本次POST的值与SESSION
		/*import ( "@.ORG.Session" );
		$Session 		= 	new Session();   ///初始化分页对象
		$Session->setLocal('post_'.MODULE_NAME.'_'.ACTION_NAME,$_POST); ///设置本地化Session癿值
		$Session->set('_output_sql_',$model->getLastSql()); */
	}
	return	$assign_array;
}

/**
 * 统计合计SQL的总数量
 *
 * @param string $sql
 * @return int
 */
function _listStatCount($sql,$cache=true){ 
	///如果是翻找下一页先找下是否有历史缓存信息
//	if ($_REQUEST['nextPage']>1 ){  
//		$rs	= _getSCacheListInfo('count');
//		if ($rs!=false){
//			return $rs;
//		}
//	}
	
	$cModel	=	M();
	$sql_count = 'select count(*) as count_stat
				from ('.$sql.') as tmp
				 ';
	if ($cache){
		$cModel->cache();
	} 
	$info	=	$cModel->query($sql_count);
	
	return  is_array($info)?$info[0]['count_stat']:0;
}


/**
 * 统计列表总合计
 *
 * @param unknown_type $sql
 * @return unknown
 */
function _listStatTotal($sql){ 
//	if ($_REQUEST['nextPage']>1 ){  
//		$rs	= _getSCacheListInfo('all_total');
//		if ($rs!=false){
//			return $rs;
//		}
//	}  
	$model	= M();
	$list	= _formatList($model->cache()->query($sql),null,0); 
//	_addSCacheListInfo('all_total',$list['list'][0]);
	return $list['list'][0]; 
}


/**
 * 获取统计缓存记录
 *
 * @param unknown_type $key
 * @return unknown
 */
function _getSCacheListInfo($key=null){
	$cacheName	=	'tablelist_'.USER_ID.'_'.ACTION_NAME.'_'.MODULE_NAME; 
	$cacheInfo	=	S($cacheName);
	if (is_array($cacheInfo)){ 
		if ($key){
			return $cacheInfo[$key];
		}else{
			return $cacheInfo;
		} 
		$requery_time	=	$_REQUEST['REQUEST_TIME']?$_REQUEST['REQUEST_TIME']:$_SERVER['REQUEST_TIME'];
		$view       	= Think::instance('View');
		$view->assign ( 'request_time',$_REQUEST['REQUEST_TIME']);
		
	}else{
		return false;
	}
}

/**
 * 统计缓存记录
 *
 * @param unknown_type $key
 * @param unknown_type $value
 */
function _addSCacheListInfo($key,$value){
//		$cacheName	=	'tablelist_'.USER_ID.'_'.ACTION_NAME.'_'.MODULE_NAME.'_'.$_SERVER['REQUEST_TIME'];
		///判断历史信息是否存在 
		$cacheName	=	'tablelist_'.USER_ID.'_'.ACTION_NAME.'_'.MODULE_NAME;
		$cache_info	=	_getSCacheListInfo(); 
		if ($cache_info==false){//数组不存在
			$cache_info	=	array( 
								$key=>$value,
								);
		}else{
			$cache_info[$key]	=	$value;
		}
		S($cacheName,$cache_info,180);
		$view       = Think::instance('View'); 
		$view->assign ('request_time',$_SERVER['REQUEST_TIME']);  
}

/**
      
     * 提供统计方面的分页
     * 返回SQL对应的数组
      
     * @access protected
      
     * @param Model $sql sql 
     * @param Model $cache 缓存 
      
     * @return void
      
     * @throws ThinkExecption
      
     */
function _listStat($sql,$cache=true) {
	$count	=	_listStatCount($sql,$cache);
	if ($count > 0) {
		$model	=	M();
		import("ORG.Util.Page");
		///			import ( "@.ORG.Page" );
		///创建分页对象
		$listRows=	(! empty ( $_REQUEST ['listRows'] ))?$_REQUEST ['listRows']:'';
		///实例化分页对象
		$p = new Page ( $count, $listRows );
		///模型对象$options条件赋值

		$sql	=	$sql.' limit '.$p->firstRow.' , '.$p->listRows.' ';
		///获取列表信息->分页查询数据
		$voList = $model->query($sql); 
		///分页显示
		$page = $p->show ();
		///列表排序显示
		$sortImg = $sort; ///排序图标
		$sortAlt = $sort == 'desc' ? L('SORT_ASC') : L('SORT_DESC'); ///排序提示
		$sort = $sort == 'desc' ? 1 : 0; ///排序方式
		$assign_array = array();
		$assign_array = $voList;
		///模板赋值显示
		$view       = Think::instance('View');
		$view->assign ( 'sort', $sort );
		$view->assign ( 'order', $order );
		$view->assign ( 'sortType', $sortAlt );
		$view->assign ( "page", $page );///页码 
		 
//		_addSCacheListInfo('count',$count); 
	}
	return	$assign_array;
}


/**
     * 更新客户款项
     *
     * @param $args 参数
     */
function Funds($args,$object_type,$action=null){

	$model_type	=	FundsObject();
	///		import('Dzh.Model.Funds.AbsFunds');
	if(!isset($model_type[$object_type])) {
		throw_exception('Funds'.$object_type.'不存在！');
	}
	$model_name	= $model_type[$object_type];
	$o 			= D($model_name);
	///     	import('Dzh.Model.Funds.'.$model_name);
	///     	$o  = self::instance($model_name);
	if ($action=='delete'){	$action	=	'deleteOp';	}
	return $o->paidDetail($args,$action);
}

/**
 * object_id对应的Model文件
 *
 * @return string
 */
function FundsObject(){
	$_paid_detail_object_type	=	array(
	1=>'ComCashIni',///公司现金期初
	101=>'ClientIni',///客户期初欠款
	102=>'ClientOtherArrearages',///客户其他欠款
	103=>'ClientFunds',///客户不指定收款
	104=>'ClientFundsCloseOut',///客户付款平帐

	120=>'ClientSale',///销售单客户欠款
	121=>'ClientSaleAdvance',///销售单预收款
	122=>'ClientSaleCloseOut',///销售单指定平帐
	123=>'ClientReturnSale',///退货
	124=>'ClientDelivery',///销售单实际发货
	129=>'ClientCheckAccount', /// 客户对账

	201=>'FactoryIni',///厂家期初欠款
	202=>'FactoryOtherArrearages',///厂家其他欠款
	203=>'FactoryFunds',///厂家不指定收款
	204=>'FactoryFundsCloseOut',///厂家付款平帐

	220=>'FactoryInstock',///入库欠款
	221=>'FactoryOnRoad',///厂家装柜在路上的款项
	229=>'FactoryCheckAccount', /// 厂家对账

	301=>'LogisticsIni',///物流期初欠款
	302=>'LogisticsOtherArrearages',///物流其他欠款
	303=>'LogisticsFunds',///物流不指定收款
	304=>'LogisticsFundsCloseOut',///物流付款平帐

	320=>'LogisticsInstock',///物流入库欠款
	329=>'LogisticsCheckAccount', ///物流公司对账

	800=>'OtherExpenses',///公司其他支出
	801=>'OtherRevenue',///公司其他收入


	);
	return $_paid_detail_object_type;
}


/**
     * 银行中心
     *
     * @param $args 参数
     */
function BankCenter($args,$object_type,$action=null){
	if(empty($object_type) || $object_type<=0){
		throw_exception('BankCenter方法中'.$object_type.'$object_type不存在！');
	}
	$model_type	=	BankCenterObjectType();
	$model_name	=	$model_type[$object_type].'';
	$o 			= D($model_name);
	if ($action=='delete'){	$action	=	'deleteOp';	}
	return $o->paidDetail($args,$action);
}

/**
 * 定义银行款项数组值
 *
 * @return  array
 */
function BankCenterObjectType(){
	$bank_object_type	=		array(
	1=>'BankIni',		///银行账号期初
	2=>'BankJournal',	///银行存取款
	3=>'BankRemittance',///银行汇款
	4=>'BankOther',		///银行其他转入
	);
	return $bank_object_type;
}


/**
 * 获取最大平账或者总平日期
 *
 * @param  int $comp_type
 * @param  int $basic_id
 * @param  int $comp_id
 * @param  int $currency_id
 * @return  string
 */
function getMaxCloseOutDate($comp_type,$basic_id,$comp_id,$currency_id){
	if ($comp_type>0 && $basic_id>0 && $comp_id>0 && $currency_id>0){
		/// 对账日期不能小于上次的对账日期
		$model	=	M('PaidDetail');
		$info 	= $model->query(' select DATE_ADD(paid_date, INTERVAL 1 DAY) as tp_max from paid_detail where currency_id='.$currency_id.' and object_type_extend in (3,4) and to_hide=1 and basic_id='.$basic_id.' and comp_type='.$comp_type.' and comp_id='.$comp_id.' group by paid_date order by paid_date desc limit 1');
		$min_paid_date	=	$info[0]['tp_max'];
	}
	return $min_paid_date;
}


/**
 * 进货分析/客户交易统计中的日期处理
 *
 * @param  date $from_date
 * @param  date $to_date
 * @param  int $type
 * @return  date
 */
function cacuDate($from_date, $to_date, $type) {
	$to_date 		= strtotime(formatDate($to_date));
	$from_date		= strtotime(formatDate($from_date));
	if ($type == 1) { /// 按年
		$year_d		= date('Y', $to_date) - date('Y', $from_date);
		if ($year_d >= 0) {
			for($i=0;$i<=$year_d;$i++) {
				$dates[] = date('Y', $from_date)+$i;
			}
		}
	}elseif ($type == 2) { /// 按月
		$month_d 	= (date('Y', $to_date) - date('Y', $from_date))*12
		+date('m', $to_date)-date('m', $from_date);
		if ($month_d >= 0) {
			for($i=0;$i<=$month_d;$i++) {
				$dates[] = date('Y-m', mktime(0,0,0,date('m',$from_date)+$i,1,date('Y',$from_date)));
			}
		}
	}elseif ($type == 3) { /// 按日
		$day_d		= round(($to_date - $from_date)/3600/24);
		if ($day_d >= 0) {
			for($i=0;$i<=$day_d;$i++) {
				$dates[] = date('Y-m-d', mktime(0,0,0,date('m',$from_date),date('d',$from_date)+$i,date('Y',$from_date)));
			}
		}
	}
	return $dates;
}


/**
 * 获取指属性的条形码长度，未设置返回空
 *
 * @param string $pre_name
 * @return int
 */
function getBarcodeLen($pre_name){
	if (!C('barcode')) return 0;
	///		if (empty($pre_name)) {
	$barcode = C('barcode_rules');
	///		}
	return $barcode['barcode'][$pre_name];
}

/**
 * 获取条形码是否可变
 *
 * @param  string $pre_name
 * @return  bool
 */
function getBarcodeExchange($pre_name){
	if (!C('barcode')) return false;
	$barcode = C('barcode_rules');
	return $barcode['barcode_exchange'][$pre_name]==1?true:false;
}


/**
 * 通过条形码回返颜色尺寸
 *
 * @param  string $barcode_no
 * @return array
 */
function inputBarcode($barcode_no){
	if(empty($barcode_no)) {
		return false;
	}
	$barcode=	M('barcode');
	$info	=	$barcode->field('p_id,barcode_no,color_id,size_id')->where('barcode_no=\''.$barcode_no.'\'')->find();
	if(!is_array($info)) {
		return false;
	}
	return $info;
}

/**
 * 通过产品/颜色等找条形码
 *
 * @param  int $p_id
 * @param  int $color_id
 * @param  int $size_id
 * @return  string
 */
function getBarcode($p_id, $color_id  = 0, $size_id = 0){
	///开启条形码
	if (C('barcode')==1){
		$barcode		= C('barcode_rules');
		$cache_barcode 	= $barcode['barcode'];
		if (!is_array($cache_barcode)) {
			return false;
		}
		$where = 'p_id='.$p_id;
		if ($cache_barcode['barcode']['color_no']>0 && $color_id) {
			$where.=' and color_id='.$color_id;
		}
		if ($cache_barcode['barcode']['size_no'] >0 && $size_id) {
			$where.=' and size_id='.$size_id;
		}
		$model	= M("Barcode");
		$barcode =$model->where($where)->select();
		if (count($barcode)==1) {
			return $barcode[0]['barcode_no'];
		}
		return false;
	}
}

/**
 * 通过产品号把相对应的条形码压入内存
 *
 * @param int $id
 */
function getProductBarCodeCache($id){
	$where	=	'p_id='.$id;
	$model	= 	M("Barcode");
	$list =$model->where($where)->select();
	foreach ((array)$list as $key=>$row) {
		$insertCache[$id][$row['color_id']][$row['size_id']]	=	$row['barcode_no'];
	}
	insertProductBarCodeCache($id,$insertCache);
	return $insertCache[$id];
}

/**
 * 对应的产品ID的条形码压入内存
 *
 * @param int $id
 * @param array $insertCache
 */
function insertProductBarCodeCache($id,$insertCache){
	$name	=	'barcode_'.$id;
	S($name,'');
	S($name,$insertCache[$id]);
}



/**
 * 发送邮件
 *
 * @param array $toArray 需要发送的地址
 * @param string $title   邮件抬头
 * @param string $content 邮件内容
 */
function postEmail($toEmail,$title,$content){

	try {
		$title			=	'友拓通-邮件提醒';///主题
		$email_adder	=	C('email_adder')?C('email_adder'):'name@domain.com';
		$email_password	=	C('email_password')?C('email_password'):'password';
		$email_host		=	C('email_host')?C('email_host'):'mail.yourdomain.com';
		$email_port		=	C('email_port')?C('email_port'):'25';
		$email_title	=	C('email_title')?C('email_title'):'友拓通';

		import("ORG.Util.Phpmailer");
		$mail = new PHPMailer(true); ///New instance, with exceptions enabled
		$body             = $content;
		///				$body             = preg_replace('/\\\\/','', $body); ///Strip backslashes

		$mail->IsSMTP();                           /// tell the class to use SMTP
		$mail->SMTPAuth   = true;                  /// enable SMTP authentication
		$mail->CharSet    =	'utf-8';                  /// enable SMTP authentication
		$mail->Port       = $email_port;                    /// set the SMTP server port
		$mail->Host       = $email_host; /// SMTP server
		$mail->Username   = $email_adder;     /// SMTP server username
		$mail->Password   = $email_password;            /// SMTP server password
		$mail->FromName 	='发件人';//phpmailer设置指定发件人
		

		$mail->IsSendmail();  /// tell the class to use Sendmail

		$mail->AddReplyTo($email_adder,$email_title);

		$mail->From       = $email_adder;
		$mail->FromName   = $email_title;

		$to = $toEmail;

		$mail->AddAddress($to);

		$mail->Subject  = $title; 

		$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; /// optional, comment out and test
		$mail->WordWrap   = 80; /// set word wrap

		$mail->MsgHTML($body);

		$mail->IsHTML(true); /// send as HTML

		$mail->Send();
		return true;
	} catch (phpmailerException $e) {
		echo $e->errorMessage();
	}
}

/**
 *导出时使用,获取想对应的$_POST
 *
 */
function getOutPutRand(){
	$rand	= $_POST['rand'] ? $_POST['rand'] :  md5(time());
	session($rand,$_POST);
	$view   = Think::instance('View');
	$view->assign('rand',$rand);
}

/**
 * 交易分析 分页 日期区间
 *
 * @param  string $sql
 * @return  array
 */
function getAnalysisDate($sql){
	$compare_type	= $_REQUEST['compare_type'];
	import("ORG.Util.Page");
	$listRows=	(! empty ( $_REQUEST ['listRows'] ))?$_REQUEST ['listRows']:'';
	$count	= M()->cache()->query('select count(*) count from ('.$sql.') t');
	///		echo M()->getLastSql();
	$count	= reset($count);
	$p 		= new Page($count['count'],$listRows);
	$page 	= $p->show();
	$limit 	= ' limit '.$p->firstRow . ','.$p->listRows;
	$order_date	= M()->cache()->query('select min(order_date) from_order_date,max(order_date) to_order_date from(select * from ('.$sql.') t  order by order_date '.$limit.') t');
	$info	= reset($order_date);
	if($compare_type==2){
		$info['from_order_date']	= $info['from_order_date'].'-01';
		$info['to_order_date']		= $info['to_order_date'].'-'.date('t',strtotime($info['to_order_date']));
	}elseif($compare_type==1){
		$info['from_order_date']	= $info['from_order_date'].'-01-01';
		$info['to_order_date']		= $info['to_order_date'].'-12-31';
	}
	$info['page']	= $page;

	return $info;
}

/**
 * 取目录下所有文件
 *
 * @param string $dir_now 目录路径
 * @param bool $postfix
 * @param string $mark
 * @return array
 */
function getAllFile($dir_now,$postfix=false,$mark='') {
	$dir_now_file = scandir($dir_now, 1);///目录中文件
	if(!is_array($dir_now_file)) {return $lang=array();}
	///获取需要便利的语言包 语言包必须包含-符号
	foreach ($dir_now_file as $dir_file) {
		if ($postfix==true) {
			if (in_array($dir_file,array('.','..','.svn'))) {
				continue;
			}
			if (empty($mark)) {
				$lang[]	=	$dir_file;
			}else{
				if (strpos($dir_file,$mark)) {
					$lang[]	=	$dir_file;
				}
			}
		}else {
			$lang[]	=	$dir_file;
		}
	}
	return $lang;
}